<template>
<div class="layout-app">
    <!-- 悬浮按钮 -->
    <div v-if="isMinimized" class="minimized-button" @click="restoreDialog">
      <i class="el-icon-message"></i>
    </div>
    <!-- main -->
    <el-dialog :title="dialogTitle" v-loading="loading"
       element-loading-text="..."
       element-loading-spinner="el-icon-loading"
       element-loading-background="rgba(255, 255, 255, 0.8)"
       :visible.sync="addDialogVisible" width="52%"
       v-dialogDrag :before-close="handleClose" 
	   :fullscreen="isFullscreen"
	   :show-close="false"
       custom-class="minimizable-dialog">
	   <!-- 在el-dialog的header部分添加自定义内容 -->
	   <template slot="title">
	     <div class="dialog-header">
	       <span>{{ dialogTitle }}</span>
	       <div class="header-buttons">
	   		<el-button
	   		  type="text" 
	   		  size="medium" 
	   		  @click="minimizeDialog" 
	   		  icon="el-icon-minimize"
	   		  title="最小化">
	   		</el-button>
	         <el-button 
	           type="text" 
	           size="medium" 
	           @click="toggleFullscreen"
	           :icon="isFullscreen ? 'el-icon-Nofullscreen' : 'el-icon-full-screen'"
	           :title="isFullscreen ? '退出全屏' : '全屏显示'">
	         </el-button>
	         <el-button 
	           type="text" 
	           size="medium" 
	           @click="addDialogVisible = false" 
	           icon="el-icon-close"
	           title="关闭">
	         </el-button>
	       </div>
	     </div>
	   </template>
        <!-- 新增 -->
        <div class="addAcc" ref='myBox' v-if="!isMinimized">
            <!-- tabs -->
            <div class="tabs">
                <div class="tabsMain">
                    <!-- 表单 header -->
                    <div class="headerForm">       
						<el-form ref="addForm" :rules="addFormRules" :model="addForm" label-width="82px" size="mini" :label-position="labelPosition">
                            <el-row :gutter="8">
                                <el-col :xs="val.xs" :sm="val.xs" :md="val.md" :lg="val.lg" :xl="val.xl" type="flex" v-for="(val,i) in formType" :key="i">
                                    <!-- input -->
                                    <el-form-item v-if="val.type == 'input'" :label="val.label" :prop="val.modelValue">
                                        <el-input :suffix-icon='val.prefix' v-model="$data.addForm[val.modelValue]" :placeholder="val.placeholder" :disabled="val.disabled" ></el-input>
                                    </el-form-item>
                                    <!-- textarea -->
                                    <el-form-item v-if="val.type == 'textarea'" :label="val.label" :prop="val.modelValue">
                                        <el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="$data.addForm[val.modelValue]"></el-input>
                                    </el-form-item>
                                    <!-- select -->
                                    <el-form-item v-if="val.type == 'select'" :label="val.label" :prop="val.modelValue">
                                        <el-select v-model="$data.addForm[val.modelValue]" filterable placeholder="请选择" @focus="sname(val,i)"
                                            @change="handleChange" :disabled="val.disabled">
                                            <el-option v-for="item in $data[val.op]" :key="item.id" :label="item.label" :value="item.id"> 
                                                <span style="color: #8492a6; font-size: 12px">{{ item.label }}</span></el-option>
                                        </el-select>
                                    </el-form-item>
									<!-- 在selectGYS类型的表单项中添加自定义下拉选项 -->
									<el-form-item v-if="val.type == 'selectGYS'" :label="val.label" :prop="val.modelValue">
									  <el-select 
									    v-model="$data.addForm[val.modelValue]" 
									    filterable 
									    placeholder="请选择" 
									    @focus="sname(val,i)"
									    @change="handleChange" 
									    :disabled="val.disabled">
									    
									    <!-- 自定义下拉选项头部 -->
									    <div slot="prefix" class="custom-select-header">
									      <!-- <span style="color: #606266; font-size: 12px;">没有对应的供应商？</span> -->
									      <el-button 
									        type="text" 
									        size="mini" 
									        icon="el-icon-plus" 
									        @click.stop="openAddSupplierDialog"
									        style="padding: 0 2px;">
									      </el-button>
									    </div>
									    
									    <el-option 
									      v-for="item in $data[val.op]" 
									      :key="item.id" 
									      :label="item.label" 
									      :value="item.id">
									      <span style="color: #8492a6; font-size: 12px">{{ item.label }}</span>
									    </el-option>
									  </el-select>
									</el-form-item>
                                    <!-- date -->
                                    <el-form-item v-if="val.type == 'date'" :label="val.label" :prop="val.modelValue">
                                        <el-date-picker
                                                :picker-options="pickerOptions" :disabled="val.disabled ? true : false"
                                                value-format="yyyy-MM-dd"
                                                type="date" placeholder="选择日期" v-model="$data.addForm[val.modelValue]">
                                        </el-date-picker>
                                    </el-form-item>
                                    <!-- btn -->
                                    <el-form-item v-if="val.type == 'btn'">
                                        <el-button type="primary" plain @click="clickEvents(val,i)">{{ val.label }}</el-button>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-form>
                    </div>
                    <!-- 表单数据！第二层取addForm下的list -->
                    <div class="mainForm">
                        <el-divider content-position="left">信息明细</el-divider>
                        <el-form ref="addMainForm" :rules="addMainFormRules" :model="addMainForm" label-width="82px" size="mini">
                            <el-row :gutter="8">
                                <el-col :xs="val.xs" :sm="val.xs" :md="val.md" :lg="val.lg" :xl="val.xl" type="flex" v-for="(val,i) in formMainType" :key="i">
                                    <!-- select one -->
                                    <el-form-item v-if="val.type == 'selectFirst'" :label="val.label" :prop="val.modelValue">
                                        <el-select v-model="$data.addMainForm[val.modelValue]" clearable  filterable
										   @focus="handlefoucs(val,i)" @change="handleChangeDrug" @clear="clearSelect" :filter-method="searchMethod" :popper-append-to-body="false">
                                            <el-group>
                                              <!-- 固定头部 -->
                                              <div class="select-header" slot="header"
                                                style="font-size: 12px;font-weight: bold;display: flex;justify-content: space-around;padding: 8px;text-align: left;
                                                position: sticky;top:0;z-index: 10;background-color: #f1f1f1;">
                                                <span style="text-align:center;">库存序号</span>
                                                <span>药品名称</span>
                                                <span>药品规格</span>
												<span>库存数量</span>
                                                <span>批次号</span>
												<span>生产厂家</span>
                                              </div>
                                              
                                              <!-- 选项内容 -->
                                              <el-option 
                                                v-for="item in filteredNameOption" 
                                                :key="item.id" 
                                                :label="item.label" 
                                                :value="item.id"
                                                :disabled="item.disabled"> 
                                                <div id="optionItem">
                                                  <span style="text-align:center;">{{ item.id }}</span>
                                                  <span>{{ item.drugName }}</span>
                                                  <el-tooltip class="item" effect="light" :content="item.drugSpec" placement="top">
                                                    <span>{{ item.drugSpec }}</span>
                                                  </el-tooltip>
                                                  <span>{{ item.purcCnt }}</span>
                                                  <span>{{ item.manuLotnum }}</span>
												  <span>{{ item.prodentpName }}</span>
                                                </div>
                                              </el-option>
                                            </el-group>
										</el-select>
                                    </el-form-item>
                                    <!-- select -->
                                    <el-form-item v-if="val.type == 'select'" :label="val.label" :prop="val.modelValue">
                                        <el-select v-model="$data.addMainForm[val.modelValue]" :disabled="val.disabled ? disabled : val.disabled" filterable>
                                            <el-option v-for="item in $data[val.op]" :key="item.id" :label="item.label" :value="item.id">
                                                <span style="font-size: 12px">{{ item.label }}</span></el-option>
                                            </el-option>
                                        </el-select>
                                    </el-form-item>
									<!-- input 数量 -->
									<el-form-item v-if="val.type == 'inputNum'" :label="val.label" :prop="val.modelValue">
										<el-input placeholder="" v-model="$data.addMainForm[val.modelValue]" class="input-with-select" @input="gotoPrice">
										    <el-select v-model="purcType" slot="prepend" @change="SelectedPurcType" placeholder="库存类型"
											style="width: 98px;">
										      <el-option label="最小单位" value="1"></el-option>
										      <el-option label="包装单位" value="2"></el-option>
										    </el-select>
										    <span slot="append" icon="el-icon-search">{{ purcType == 1 ? minUnt : unt }}</span>
										  </el-input>
										<!-- <el-input :suffix-icon='val.prefix' v-model="$data.addMainForm[val.modelValue]" @blur="handleInput(val,i)" :disabled="val.disabled" ></el-input> -->
									</el-form-item>
                                    <!-- input -->
                                    <el-form-item v-if="val.type == 'input'" :label="val.label" :prop="val.modelValue">
                                        <el-input :suffix-icon='val.prefix' v-model="$data.addMainForm[val.modelValue]" @input="handleInput(val,i)" 
                                                  :disabled="val.disabled"></el-input>
                                    </el-form-item>
                                    <!-- textarea -->
                                    <el-form-item v-if="val.type == 'textarea'" :label="val.label" :prop="val.modelValue">
                                        <el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="$data.addMainForm[val.modelValue]"
                                                  :disabled="val.disabled"></el-input>
                                    </el-form-item>
                                    <!-- date -->
                                    <el-form-item v-if="val.type == 'date'" :label="val.label" :prop="val.modelValue">
                                        <el-date-picker class="autoWidth" :picker-options="pickerOptions" :disabled="val.disabled"
                                                        type="date" placeholder="选择日期" v-model="$data.addMainForm[val.modelValue]">
                                        </el-date-picker>
                                    </el-form-item>
                                    <!-- btn -->
                                    <el-form-item v-if="val.type == 'btn'">
                                        <el-button type="primary" plain @click="clickEvents(val,i)">{{ val.label }}</el-button>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-form>
                    </div>
                    <!-- table -->
                    <div class="table">
                        <el-table :data="tableData" border 
						  :style="{ width: tableWidth + 'px' }"
						  :cell-class-name="tableCellClassName" 
						  @row-dblclick="dbclick" 
                        >
							<el-table-column prop="purcType" label="库存类型">
								<template slot-scope="{ row }">
									<span :style="{ color: purcTypeColorMap[row.purcType] }">{{ purcTypeMap[row.purcType] || '未知' }}</span>
								</template>
							</el-table-column>
                            <!-- 字段映射 -->
                            <el-table-column prop="drugName" label="药品名称" align='center' width="128"></el-table-column>
                            <el-table-column prop="drugCode" label="药品编码" align='center' width="128"></el-table-column>
                            <el-table-column prop="drugSpec" label="规格描述" align='center' width="168"></el-table-column>
                            <!-- 在el-table-column中添加可编辑列 -->
                            <el-table-column prop="apllyAmt" label="出库数量">
                              <template slot-scope="scope">
                                <el-input 
                                  v-if="scope.row.editing"
                                  v-model.number="scope.row.apllyAmt"
                                  size="mini"
                                  :max="scope.row.purcCnt"
                                  @change="handleAmountChange(scope.row)"
                                  :title="`最大可出库数量：${scope.row.purcCnt}`"
                                ></el-input>
                                <span v-else>{{ scope.row.apllyAmt + scope.row.unt }}</span>
                              </template>
                            </el-table-column>
							<el-table-column prop="unt" label="出库单位"></el-table-column>
                            <el-table-column prop="manuLotnum" label="生产批号"></el-table-column>
							<el-table-column prop="expyDate" label="有效日期" width="168px"></el-table-column>
							<el-table-column prop="prodentpName" label="生产厂家" align='center' width="168"></el-table-column>
							<el-table-column v-for="(col, inx) in tableRows" :key="inx" :type="col.type" :prop="col.prop" :label="col.name" :width="columnWidth(col, tableData)"></el-table-column>
							<!-- fixed -->
							<el-table-column
							  fixed="left" 
							  label="行号" 
							  width="68" 
							  align="center">
							  <template slot-scope="scope">
							    {{ scope.$index + 1 }}
							  </template>
							</el-table-column>
							<!-- edit -->
							<el-table-column fixed="right" label="操作" width="168">
							  <template slot-scope="scope">
							    <div class="edit-actions">
							      <template v-if="!scope.row.editing">
							        <el-button 
							          type="primary" 
							          size="mini"
							          @click="enableEditing(scope.row)"
							          :title="`当前库存：${scope.row.purcCnt}`"
							          :disabled="isEditing"
							        >编辑</el-button>
							        <el-button 
							          type="danger" 
							          size="mini"
							          @click="deleteRow(scope.$index)"
							          :disabled="isEditing"
							        >删除</el-button>
							      </template>
							      <template v-else>
							        <el-button 
							          type="success" 
							          size="mini"
							          @click="saveEdit(scope.row)"
							          :disabled="scope.row.apllyAmt > scope.row.purcCnt"
							        >保存</el-button>
							        <el-button 
							          type="info" 
							          size="mini"
							          @click="cancelEdit(scope.row)"
							        >取消</el-button>
							      </template>
							    </div>
							  </template>
							</el-table-column>
                        </el-table>
                        <div class="total">
                            <span>成本合计：</span><el-input v-model="cbValue" style="width: 88px;" size="mini" :disabled='totaldisabled'></el-input>
                            <span style="margin-left: 12px;">零售合计：</span><el-input v-model="lsValue" style="width: 88px;" size="mini" :disabled='totaldisabled'></el-input>
                        </div>
                    </div>
                </div>
            </div>
              <div slot="footer" class="dialog-footer" v-if="!isEditShow">
                <el-button size="mini" :disabled="isEditing" type="info" plain @click="draftSubmit">存为草稿</el-button>
                <el-button size="mini" :disabled="isEditing" type="primary" plain @click="addSubmit">保存提交</el-button>
                <el-button size="mini" :disabled="isEditing" plain @click="minimizeDialog">最小化</el-button>
              </div>
			  <!-- 编辑提交 -->
			  <div slot="footer" class="dialog-footer" v-if="isEditShow">
			  	<!-- <el-button :loading="loading" size="mini" type="warning" plain @click="gotoPlan">采购计划</el-button> -->
			  	<el-button :loading="loading"  :disabled="isEditing" size="mini" type="info" plain @click="draftEditSubmit">修改保存草稿</el-button>
			  	<el-button :loading="loading"  :disabled="isEditing" size="mini" type="primary" plain @click="editSubmit">修改提交</el-button>
			  	<el-button :loading="loading"  :disabled="isEditing" size="mini" plain @click="minimizeDialog">最小化</el-button>
			  </div>
        </div>
    </el-dialog>
    <!-- 内层Model -->
    <div class="innerModel">
        <!-- 在模板底部添加新增供应商对话框 -->
          <el-dialog
            title="新增供应商"
        	:visible.sync="addSupplierDialogVisible"
            width="48%"
          	top="18px"
            @close="handleSupplierDialogClose"
          >
            <el-form
              ref="supplierForm"
              :model="supplierForm"
              :rules="rules"
              label-width="120px"
              label-position="right"
            >
              <el-form-item label="供应商名称" prop="supplierName">
                <el-input
          			  size="mini"
                  v-model="supplierForm.supplierName"
                  placeholder="请输入供应商名称"
                  clearable
                />
              </el-form-item>
          
              <el-form-item label="联系人" prop="contact">
                <el-input
          			  size="mini"
                  v-model="supplierForm.contact"
                  placeholder="请输入联系人姓名"
                  clearable
                />
              </el-form-item>
          
              <el-form-item :label="phoneType === 'mobile' ? '手机号：' : '座机号：'" prop="contactPhone">
                <el-input
        			size="mini"
                  v-model="supplierForm.contactPhone"
                  placeholder="请输入手机号或座机号"
                  @blur="handlePhoneBlur"
                  clearable
                />
              </el-form-item>
          
              <el-form-item label="许可证号" prop="permitNumber">
                <el-input
          			  size="mini"
                  v-model="supplierForm.permitNumber"
                  placeholder="请输入许可证号"
                  clearable
                />
              </el-form-item>
          
              <el-form-item label="地址" prop="address">
                <el-input
          			  size="mini"
                  v-model="supplierForm.address"
                  placeholder="请输入详细地址"
                  clearable
                />
              </el-form-item>
          
              <el-form-item label="状态" prop="status">
                <el-radio-group v-model="supplierForm.status">
                  <el-radio :label="1">启用</el-radio>
                  <el-radio :label="2">禁用</el-radio>
                </el-radio-group>
              </el-form-item>
          
              <el-form-item label="备注" prop="remark">
                <el-input
				  size="mini"
                  v-model="supplierForm.remark"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入备注信息"
                />
              </el-form-item>
            </el-form>
          
            <div slot="footer" class="dialog-footer">
              <el-button size="mini" type="primary" @click="handleSubmit" :loading="loading">确 定</el-button>
              <el-button size="mini" @click="addSupplierDialogVisible = false">取 消</el-button>
            </div>
        
        </el-dialog>
    </div>

</div>
</template>

<script>
// self
import AccType from './addReturnType.js'
import AccMainType from './AddReturnMainType.js'
import addForm from './addForm.js' //Form表单
// prop

// 接口
import { getTretn } from "@/api/PSI/shopReturn.js"; // 出库方式

import { tcmRetnInsert,edittcmRetn,tcmRetnselectTcmList,selectDropDownList,purcRetnjoin,getTcmRetnList } from "@/api/MedicenHouse/traMedici.js";
import { addSupplierEntity,SupplierDetails,editSupplierEntity }  from "@/api/supplier.js";
export default {
	inject: ['reload'], // 无痕刷新
    components:{
        
    },
    data(){
        //表单校验取大于0的数字型数据
        var validatePercentage = (rule, value, callback) => { 
            if(value == ''){
                return callback(new Error('出库数量不能为空！'));  
            } else if(value > this.addMainForm.purcCnt){
                return callback(new Error('出库数量不能大于已有的库存数量！'));  
            }
          callback();
        };
        return{
            //str
            dialogTitle:'新建其他出库【中药房】',
			// 新增全屏状态
			isFullscreen: false,
			packNum:0,
			getMinMax:0,
			purcType:'2', // 库存类型 = > 判断大小单位 1最小单位,2包装单位
			unt:'', // 包装单位 （数量：盒？包？g?）
			minUnt:'', // 最小单位 （数量：盒？包？g?）
            tableWidth:'', //右侧表格动态宽度
            labelPosition:'right',
            dosUnt:'?', // 动态包装单位
            value:'',
            inputSearchValue:'',
            deptCode:'',
            getLunarDay: '',
            drugName:'',
            appId:'', // * 选择采购计划时的Id
            startDate:'', // * 开始时间
            endDate:'', // * 结束时间
            idx:'',
            cbValue:'',
            lsValue:'',
            currentCell: null, // 单元格隐藏
            year: new Date().getFullYear(),
            month: new Date().getMonth() + 1,
            date: new Date().getDate(),
            lunarDate: '',//农历
            // 1 - 3
            firstName:'',
            seconedName:'',
            thirdName:'',
            auditStatus:'5',
            currentRow: null, //单选高亮
            //num
            pageNum: 1, //当前页currentPage
            pageSize: 6,
            KcNum:0, // 库存数量
            totalSize: 10, //总条数
            //ble
            loading:false,
            disabled:true,
            totaldisabled:true,
            isMinimized: false,
            addghdwDialog:false,
            selectDisabled:true,
			isEditShow:false,
            addDialogVisible: false, //新增采购入库model
            dialogFormVisible:false,
            innerVisible:false, //内层Model选择采购计划
			oldData: {}, // 用于保存编辑前的数据
			formMainType: [], // 确保初始化为数组
			feetBtn: [], // 确保初始化为数组
			tableData: [], // 确保初始化为数组
			// 添加编辑状态控制变量
			editingRow: null,
			// 添加编辑状态控制变量
			isEditing: false, // 控制是否处于编辑状态
			editDisabledMap: {}, // 用于记录每行的编辑按钮禁用状态
            //arr
            formType:[], // 表单头部内容

            tableRows:[
                { name:"库存数量", prop:"purcCnt", type:"" },
                { name:"成本单价", prop:"retnPric", type:"" },{ name:"成本金额", prop:"retnAmt", type:"" },
                { name:"零售单价", prop:"salePric", type:"" },{ name:"零售金额", prop:"saleAmt", type:"" },
            ],
            innertableData:[], //内层采购计划数据源
            currentObj:{}, //内层采购计划数据源 = > 单击选择
            currentTable: [],//表格单选
            selectOption:[{id:4,label:'中药房'}],//库房
            stateOptions:[{id:0,label:'草稿'},{id:2,label:'提交'}],
            kcOptions:[{id:1,label:'最小单位',value:'最小单位'},{id:2,label:'包装单位',value:'包装单位'}], // 库存类型
            ghdwOption:[
                {id:1,label:'水富市人民医院',value:'水富市人民医院'},{id:2,label:'昆明灵泽科技有限公司',value:'昆明灵泽科技有限公司'},
            ],
			purcTypeMap:{
				1: '最小单位',
				2: '包装单位',
			},
			purcTypeColorMap: {
				1: '#67C23A',
				2: '#409EFF',
			},
            retnTypeOptions:[
                {id:1,label:'采购退库',value:'采购退库'},{id:2,label:'报损出库',value:'报损出库'},{id:3,label:'过期出库',value:'过期出库'},
                {id:4,label:'捐赠出库',value:'捐赠出库'},{id:5,label:'其他出库',value:'其他出库'},{id:6,label:'输错出库',value:'输错出库'},
                {id:7,label:'科室出库',value:'科室出库'},{id:8,label:'销售出库',value:'销售出库'},{id:9,label:'拆零自动出库',value:'拆零自动出库'},
            ],
            // 表单验证规则 header
            addFormRules:{
                shedId: [{ required: true, message: '请先选择要入库的库房！', trigger: 'change' }],
                supplyCandidateId: [{ required: true, message: '请选择供货单位！', trigger: 'change' }],
                cglb: [{ required: true, message: '采购类别不能为空！', trigger: 'change' }],
            },
            // 表单验证规则 main
            addMainFormRules:{
                drugId: [{ required: true, message: '请先选择药品信息！', trigger: 'change' }],
                manuLotnum: [{ required: true, message: '请输入药品的生产批号！', trigger: 'blur' }],
				retnCnt: [
					{ required: true, message: '出库的数量为必填项！', trigger: 'blur' },
					{ 
					  validator: (rule, value, callback) => {
						// 验证是否为非0正整数
						if (!/^[1-9][0-9]*$/.test(value)) {
						  callback(new Error('出库的数量为非0正整数!'));
						} else {
						  callback();
						}
					  },
					  trigger: 'blur'
					}
				],
                expyDate: [{ required: true, message: '药品的有效日期不能为空！', trigger: 'change' }],
                purcType: [{ required: true, message: '请先选择库存类型！', trigger: 'change' }],
            },
			addSupplierDialogVisible: false,
			supplierForm: {
			  supplierName: '',
			  contact: '',
			  contactPhone: '',
			  permitNumber: '',
			  address: '',
			  status: 1, // 默认启用
			  remark: ''
			},
            // 单据状态 0 草稿,1 回退提交,2 已提交,3 回退审核,4 已审核,5 已过单,6 已作废'
            statusOption:[
                {id:0,label:'草稿'},{id:1,label:'回退提交'},{id:2,label:'已提交'},{id:3,label:'回退审核'},{id:4,label:'已审核'},{id:5,label:'已过单'},{id:6,label:'已作废'},
            ],
            sexOptions:[{id:1,label:'男',value:'男'},{id:2,label:'女',value:'女'}],
            marryiedOptions:[{id:1,label:'未婚',value:'未婚'},{id:2,label:'已婚',value:'已婚'},{id:3,label:'离异',value:'离异'},{id:4,label:'丧偶',value:'丧偶'},{id:5,label:'再婚',value:'再婚'}],
            nameOption:[],
            ckWaysOptions:[],
            //obj
            addForm:{}, // form表单 * 
            addMainForm:{}, // form主体表单 * addForm.list
            lists:{},
            options:[],
            ssrOption:[],
            gysOption:[],
            ManufacturerOptions:[],
            //props
			pickerOptions: {},
			expyDatePickerOptions: {
				disabledDate(time) { return time.getTime() < Date.now() },
				shortcuts: [
					{ text: '三个月后',onClick(picker) {const date = new Date();date.setTime(date.getTime() + 3600 * 1000 * 24 * 90);picker.$emit('pick', date);}},
					{ text: '半年后',onClick(picker) {const date = new Date();date.setTime(date.getTime() + 3600 * 1000 * 24 * 180);picker.$emit('pick', date);}},
					{ text: '明年',onClick(picker) {const date = new Date();date.setTime(date.getTime() + 3600 * 1000 * 24 * 360);picker.$emit('pick', date);}},
					{ text: '后年',onClick(picker) {const date = new Date();date.setTime(date.getTime() + 3600 * 1000 * 24 * 720);picker.$emit('pick', date);}},
					{ text: '三年后',onClick(picker) {const date = new Date();date.setTime(date.getTime() + 3600 * 1000 * 24 * 360 * 3);picker.$emit('pick', date);}},
					{ text: '五年后',onClick(picker) {const date = new Date();date.setTime(date.getTime() + 3600 * 1000 * 24 * 360 * 5);picker.$emit('pick', date);}},
					{ text: '十年后',onClick(picker) {const date = new Date();date.setTime(date.getTime() + 3600 * 1000 * 24 * 360 * 10);picker.$emit('pick', date);}},
				]
			},
			// 在data中添加watch属性 , 使表格能随着 addMainForm 的变化而更新数据。主要需要修改 enableEditing 方法和添加对 addMainForm 的监听。
			watch: {
			  addMainForm: {
			    handler(newVal) {
			      if (newVal.editing) {
			        // 找到表格中对应的行并更新
			        const index = this.tableData.findIndex(item => item.drugId === newVal.drugId);
			        if (index !== -1) {
			          this.$set(this.tableData, index, newVal);
			        }
			      }
			    },
			    deep: true
			  }
			}
        }
    },
	// 在data中添加一个计算属性来过滤nameOption
	// 在computed中添加过滤逻辑
	computed: {
	  filteredNameOption() {
	    // 获取表格中所有的厂家信息
	    const existingManufacturers = this.tableData.map(item => ({
	      prodentpName: item.prodentpName
	    }));
	    
	    // 过滤掉已经存在于表格中的药品（基于厂家ID和名称）
	    return this.nameOption.map(item => {
	      // 检查是否已存在相同的厂家
	      const isDisabled = existingManufacturers.some(manu => 
	        manu.prodentpName === item.prodentpName
	      );
	      
	      return {
	        ...item,
	        disabled: isDisabled
	      };
	    });
	  }
	},
    created() {
        
    },
    mounted() {
        // 获取接口参数
        this.getAddForm();
        this.ckWays();
        this.getGys();
        // 获取当前日期时间
        this.getNowDateTime();
    },
    methods:{
        // 采购计划数据
        async loadData(){
            let res = await getPurchasingPlan({
                auditStatus:this.auditStatus,
                startDate:this.startDate,
                endDate:this.endDate,
                pageNum:this.pageNum,
                pageSize:this.pageSize,
            });
            if(res.code == 200){
                this.innertableData = res.data.content
                this.totalSize = res.data.totalSize
            }else{
                this.$message({type: 'error',message: res.message});
            }
        },
		
        /* 退库药品数据源 */
        async getProData() {
          let res = await tcmRetnselectTcmList({
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            drugName: this.drugName
          });
          
          if (res.code === 200) {
            // 按照 drugName 进行排序
            const sortedData = res.data.content.sort((a, b) => {
              // 如果 drugName 相同，可以按照其他字段排序（如 drugId）
              if (a.drugName === b.drugName) {
                return a.drugId - b.drugId;
              }
              // 否则按照 drugName 升序排序
              return a.drugName.localeCompare(b.drugName);
            });
            
            // 将排序后的数据赋值给 nameOption
            this.nameOption = sortedData.map(obj => ({
              label: obj.drugName,
              ...obj
            }));
          } else {
            this.$message.error(res.message);
          }
        },
        /* props => 生产厂家模糊查询 */
        searchMethod(query, option) {
            console.log(query);
            if(query){
                console.log(query,'再调一次接口查询');
                this.inputSearchValue = query
                this.pageNum = 1
                this.pageSize = 10
                this.drugName = query
                this.getProData();
            }else{
                console.log('buzou');
            }
        },
        // select聚焦
        async handlefoucs(val,i){
            this.idx = i;
            console.log(i);
            switch (i) {
                case 0: // 药典名称
                    this.getProData();
					
                break;
            }
        },
        // 表格单选 => getPlan
        handleCurrentTableChange(val){
            if(val.state != 5){
                this.setCurrent();
                this.$message({ type: 'error', message: '只能选择已过单数据!'});
            }else{
                // 赋id
                this.appId = val.id
                this.currentTable = val
                this.$message({ type: 'success', message: '已选择:' + this.appId + '的采购计划数据'});
            }
        },
        // 取消高亮
        setCurrent(row) {
            this.$refs.singleTable.setCurrentRow(row);
        },
        // 表单头部聚焦事件 => addForm
        sname(v,i){
        	switch(i){
        		case 5:
        			this.getGys();
        		break;
        	}
        },
		// SelectVal to editForm
		handleChange(val) {
		  switch(this.idx) {
		    case 2: // 供货单位
		      let rs = this.gysOption.find(name => name.id === val)
		      this.addMainForm.supplierName = rs.supplierName
		      break;
		    // 添加生产厂家的处理
		    case 7: // 生产厂家
		      let manufacturer = this.prodentOption.find(item => item.id === val);
		      if (manufacturer) {
		        this.addMainForm.prodentpName = manufacturer.label; // 生产厂家名称
		        this.addMainForm.prodentpNameId = manufacturer.id; // 生产厂家ID
		        
		        // 如果药品有效期天数存在，则计算并设置有效期
		        if (this.expyDate && this.addMainForm.manuDate) {
		          const manuDate = new Date(this.addMainForm.manuDate);
		          const expyDate = new Date(manuDate.getTime() + (this.expyDate * 24 * 60 * 60 * 1000) - (24 * 60 * 60 * 1000));
		          
		          // 格式化为 yyyy-MM-dd
		          const year = expyDate.getFullYear();
		          const month = String(expyDate.getMonth() + 1).padStart(2, '0');
		          const day = String(expyDate.getDate()).padStart(2, '0');
		          
		          this.addMainForm.expyDate = `${year}-${month}-${day}`;
		        }
		      }
		      break;
		  }
		},
        // 计算总金额
        getTotalAmt(){
            let cbTotal = 0;
			let lsTotal = 0;
			if(this.tableData.length === 0){
				this.addForm.costAmt = this.addMainForm.retnAmt = this.addMainForm.retnPric * this.addMainForm.purcCnt // 成本金额
				this.addForm.saleAmt = this.addMainForm.saleAmt = this.addMainForm.salePric * this.addMainForm.purcCnt // 零售金额
				this.cbValue = this.addForm.costAmt;
				this.lsValue = this.addForm.saleAmt;
			}else{
				this.addForm.costAmt = this.addMainForm.retnAmt = this.addMainForm.retnPric * this.addMainForm.purcCnt // 成本金额
				this.addForm.saleAmt = this.addMainForm.saleAmt = this.addMainForm.salePric * this.addMainForm.purcCnt // 零售金额
				this.tableData.forEach(row => {
					cbTotal += row.retnAmt;
					lsTotal += row.saleAmt;
				});
				this.addForm.costAmt = this.cbValue = cbTotal;
				this.addForm.saleAmt = this.lsValue = lsTotal;
			}
        },
        handleInput(v,i){
            this.idx = i;
            console.log(i);
            // i event
            switch (i) {
                case 11:
                    this.getTotalAmt();
                break;
            }
        },
        // 调用接口查询是否可加入
        async isJoined() {
          // 检查是否已存在相同药品ID
          const exists = this.tableData.some(item => item.drugId === this.addMainForm.drugId);
          if (exists) {
            this.$message.error('该药品已存在于列表中！');
			// 获取表格中所有的drugId
			const existingDrugIds = this.tableData.map(item => item.drugId);
			// 过滤掉已经存在于表格中的药品
			return this.nameOption.filter(item => !existingDrugIds.includes(item.id));
          }
		  
          let reslut = await purcRetnjoin({ 
            amount: this.addMainForm.retnCnt,
            invyId: this.addMainForm.invyId,
			pacCnt:this.packNum,
			purcType:this.purcType
          });
          
          if(reslut.code === 200) {
            this.loading = true;
            setTimeout(() => {
              // 处理返回的数据，计算金额
              const processedData = reslut.data.map(item => ({
                ...item,
                saleAmt: item.salePric * item.apllyAmt,
                retnAmt: item.retnPric * item.apllyAmt
              }));
              
              if(this.tableData.length === 0) {
                // 如果表格为空，直接赋值
                this.tableData = processedData;
              } else {
                // 如果表格不为空，直接添加新数据
                this.tableData = [...this.tableData, ...processedData];
              }
              
              // 计算总金额
              this.cbValue = this.tableData.reduce((sum, item) => sum + item.retnAmt, 0);
              this.lsValue = this.tableData.reduce((sum, item) => sum + item.saleAmt, 0);
              
              // 更新表单中的总金额
              this.addForm.costAmt = this.cbValue;
              this.addForm.saleAmt = this.lsValue;
              
              this.$message.success('已添加！');
              this.loading = false;
            }, 888);
              this.$refs['addMainForm'].resetFields();
          } else {
            this.$message.error(reslut.message);
          }
        },
		// 新增切换全屏方法
		toggleFullscreen() {
		  this.isFullscreen = !this.isFullscreen;
		},
        // 循环加入按钮点击事件
        // 在clickEvents方法中添加对编辑状态的判断
        clickEvents(val, i) {
          this.idx = i;
          switch (i) {
            case 8:
              // 如果是编辑状态，则更新当前编辑的行
              if (this.addMainForm.editing) {
                this.saveEdit(this.addMainForm);
              } else {
                // 否则正常加入新数据
                this.$refs.addMainForm.validate(async(valid) => {
                  if(valid){
                    this.isJoined();
                  }
                });
              }
              break;
          }
        },
		// 库存类型选择
		SelectedPurcType(val){
			this.addMainForm.purcType = val
			console.log(this.addMainForm.purcType,'this.addMainForm.purcTypethis.addMainForm.purcType');
			if(this.addMainForm.purcType == 1){
				this.addMainForm.retnCnt = this.addMainForm.retnCnt * this.getMinMax // 最小单位成本单价
			}else{
				this.addMainForm.retnCnt = this.addMainForm.retnCnt / this.getMinMax; // 最大单位成本单价
				// 验证 retnCnt 是否为非0正整数
				  if (this.addMainForm.retnCnt) {
				    const regex = /^[1-9][0-9]*$/; // 非0正整数正则表达式
				    
				    if (!regex.test(this.addMainForm.retnCnt)) {
				      this.$message({
				        type: 'error',
				        message: '入库数量的最大单位必须是非0正整数!'
				      });
					  this.addMainForm.retnCnt = ''
				      return; // 如果验证失败，直接返回不执行后续逻辑
				    }
				  }
			}
		},
		gotoPrice(v){
			if(v.length > 5){
				this.$message({type: 'error',message: '有效数量长度最高暂时为5位数...' });
			}else if(this.purcType == 1){
				console.log(this.purcType,'输入数量leix'); // 最小单位成本单价
			}
		},
        // 查看单据数据
        watchData(){
            this.$message({type: 'waring',message: '正在开发中...' });
        },
        // 当前日期时间
        formatDate(date) {
              const year = date.getFullYear();
              const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，需要加 1
              const day = String(date.getDate()).padStart(2, '0');
              const hours = String(date.getHours()).padStart(2, '0');
              const minutes = String(date.getMinutes()).padStart(2, '0');
              const seconds = String(date.getSeconds()).padStart(2, '0');
              return `${year}-${month}-${day}`;
        },
        // 将当前日期时间设置为夜晚十一点五十九分
        getNowDateTime(){
            // 获取当前日期时间
            this.addForm.busDate = this.formatDate(new Date);
            // 获取制单人 => 当前登录用户
            this.addForm.createId = JSON.parse(localStorage.getItem('userInfo')).userId;
            this.addForm.creater = JSON.parse(localStorage.getItem('userInfo')).username;
            // 获取诊所Id => 当前登录用户
            this.addMainForm.clinicId = JSON.parse(localStorage.getItem('userInfo')).clinicId;
            // 获取终端序号 => 当前登录用户
            this.addForm.terminalId = localStorage.getItem('terminalId');
        },
        // 开始时间变化值
        startDateHandle(value){ if (value) {this.startDate = this.formatDate(value)}},
        // 结束时间变化值
        endDateHandle(value){ if (value) {this.endDate = this.formatDate(value)}},
        // 时间处理
        changDate(val){
            let i = this.idx
            switch(i) {
                case 5:
                function formatDate(date) {
                  const year = date.getFullYear();
                  const month = (date.getMonth() + 1).toString().padStart(2, '0');
                  const day = date.getDate().toString().padStart(2, '0');
                  return `${year}-${month}-${day}`;
                }
                // 使用示例
                const now = new Date();
                this.addForm.busDate = formatDate(val);
            }
        },
        // 出库方式下拉列表
        async ckWays(){
            let rs = await getTretn();
            this.ckWaysOptions = rs.data.map(obj => {
              // 将 name 替换为 label，并保留其他字段
              return { label: obj.name , ...obj };
            });
        },
        // 供应商下拉列表
        async getGys(){
            let rs = await selectDropDownList()
            this.gysOption = rs.data.content.map(obj => {
              // 将 name 替换为 label，并保留其他字段
              return { label: obj.supplierName , ...obj };
            });
        },
		// 下拉选项清空事件
		clearSelect(){
			this.getProData();
		},
        handleInputPacCut(v,i){
            this.idx = i;
            console.log(i);
            // i event
            switch (i) {
                case 8:
                let purcCntRule = /^[1-9]\d*$/;
                if(!purcCntRule.test(this.addMainForm.purcCnt)){
                    this.$message({ type: 'error', message: '请输入正确的出库数量，请注意格式!'});
                }else{
                    this.getMarkUpPric();
                    this.getPageListCheck(); // 检测库存是否充足
                }
                break;
            }
        },
        // 直接计算销售金
        getMarkUpPric(drugrs){
            this.addForm.costAmt = this.addMainForm.retnPric * Number(this.addMainForm.retnCnt)	 // 成本金额
            this.addForm.saleAmt = this.addMainForm.salePric * Number(this.addMainForm.retnCnt); // 零售金额
            this.addMainForm.retnAmt = this.addMainForm.retnPric * Number(this.addMainForm.retnCnt)	 // 成本金额 =》 明细
            this.addMainForm.saleAmt = this.addMainForm.salePric * Number(this.addMainForm.retnCnt); // 零售金额 =》 明细
            // console.log(this.addMainForm.retnPric,'怕怕怕怕怕怕怕怕怕怕怕怕怕怕怕怕怕',this.addMainForm.retnCnt);
            this.cbValue = this.addForm.costAmt
            this.lsValue = this.addForm.saleAmt
        },
        // SelectVal to editForm

        // 修改handleChangeDrug方法，确保正确设置药品信息
        handleChangeDrug(val) {
          let drugrs = this.nameOption.find(name => name.id === val)
          console.log(drugrs);
          this.getMinMax = drugrs.pacCnt // 大小单位转换
          this.addMainForm.drugId = drugrs.id // 确保设置drugId
          this.addMainForm.label = drugrs.drugName
          this.addMainForm.purcCnt = drugrs.purcCnt
          this.addMainForm.drugCode = drugrs.drugCode
          this.addMainForm.invId = this.addMainForm.invyId = drugrs.invyId
          
		  this.addMainForm.manuLotnum = drugrs.manuLotnum
          this.addMainForm.drugSpec = drugrs.drugSpec
          this.addMainForm.retnPric = drugrs.purcPric
          this.KcNum = drugrs.purcCnt // 库存数量
          this.unt = drugrs.pacUnt // 包装单位
          this.purcType = this.addMainForm.purcType = String(drugrs.purcType);
          this.minUnt = drugrs.dosUnt // 最小单位
          this.addMainForm.salePric = drugrs.salePric
          this.dosUnt = this.addMainForm.unt = drugrs.unt
          this.addMainForm.prodentpName = drugrs.prodentpName
          this.addMainForm.prodentpId = drugrs.prodentpNameId // 确保设置厂家ID
          this.addMainForm.pacCnt = this.packNum = drugrs.pacCnt // 包装数量
        },
        //新增保存
        async addSubmit(){
            //触发验证表单
            this.$refs.addForm.validate(async(valid) => {
                if(valid){
                    this.addForm.state = 2
                    this.addForm.list = this.tableData
                    console.log(this.addForm);
                    let result = await tcmRetnInsert(this.addForm)
                    if (result.code === 200) {
                        this.reload();
                        this.$message({ type: 'success', message: result.message });
                        this.addDialogVisible = false;
                    } else {
                        this.$message.error(result.message)
                    }
                }
            })
        },
		// 修改新增保存
		async editSubmit(){
            //触发验证表单
            this.$refs.addForm.validate(async(valid) => {
                if(valid){
                    this.addForm.state = 2
                    this.addForm.list = this.tableData
                    console.log(this.addForm);
                    let result = await edittcmRetn(this.addForm)
                    if (result.code === 200) {
                        this.reload();
                        this.$message({ type: 'success', message: result.message });
                        this.addDialogVisible = false;
                    } else {
                        this.$message.error(result.message)
                    }
                }
            })
        },
		checkedNum(){
			if(this.addMainForm.purcType == 1){
				this.addMainForm.retnCnt = this.addMainForm.retnCnt
			}else{
				this.addMainForm.retnCnt = Number(this.addMainForm.retnCnt) * this.packNum
			}
		},
        // 草稿保存
        async draftSubmit(){
            //触发验证表单
            this.$refs.addForm.validate(async(valid) => {
                if(valid){
                    this.addForm.state = 0
                    this.addForm.list = this.tableData
                    let result = await tcmRetnInsert(this.addForm)
                    if (result.code === 200) {
                       this.reload();
                       this.$message({ type: 'success', message: result.message });
                        this.addDialogVisible = false;
                    } else {
                        this.$message.error(result.message)
                    }
                }
            })
        },
		// 修改草稿保存
		async draftEditSubmit(){
			console.log(this.addForm,'this.addFormthis.addFormthis.addForm');
			//触发验证表单
			this.$refs.addForm.validate(async(valid) => {
			    if(valid){
			        this.addForm.state = 0
			        this.addForm.list = this.tableData
			        let result = await edittcmRetn(this.addForm)
			        if (result.code === 200) {
			            this.reload();
			            this.$message({ type: 'success', message: result.message });
			            this.addDialogVisible = false;
			        } else {
			            this.$message.error(result.message)
			        }
			    }
			})
		},
        // 父组件控制打开新增 / 编辑 模态框
		async open(param){
			console.log(param,'paprmkdajnqwjelifa;adalk;s');
			if(param.nameTitle == '新增' || param.nameTitle.includes('新增')){
				this.addDialogVisible = true;
				this.isShow = true
				this.isEditShow = false;
				this.dialogTitle = '新建其他出库【中药房】'
			}else if(param.nameTitle == '修改' || param.nameTitle.includes('修改') || param.nameTitle.includes('编辑')){
				this.addDialogVisible = true;
				this.isEditShow = true;
				this.dialogTitle = '编辑其他出库【中药房】'
				let res = await getTcmRetnList({ id:param.id });
				if(res.code === 200){
					// console.log(res.data);
					// 遍历 res.data 的所有键名
					for (let key in res.data) {
					  // 检查键名是否在对象 A 中存在
					  if (this.addForm.hasOwnProperty(key)) {
						// 如果存在，将 B 中的值更新到 A 中
						this.addForm[key] = res.data[key];
					  }
					}
					// this.addForm.markUpId == 2 ? this.addForm.markUpFixed = 1 : this.addForm.markUpFixed = 0
					console.log(this.addForm,'获取合并之后的数据');
					this.tableData = this.addForm.list
					this.addForm.id = param.id
				}
			}
		},
        // 根据选择的id去查找id对应的对象
        foundObj(){
            let rs = this.gysOption.find(name => name.id === val)
        },
        // 删除行（修正版本）
        deleteRow(index) {
            this.$confirm('确定要删除此行吗？', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              // 确保tableData存在且是数组
              if (Array.isArray(this.tableData)) {
                this.tableData.splice(index, 1);
                this.$message.success('删除成功');
                // 重新计算合计
                this.calculateTotals();
              } else {
                this.$message.error('数据异常，无法删除');
              }
            }).catch(() => {
              this.$message.info('已取消删除');
            });
        },
        handleSelectCost(val) {
          this.addForm.nativePlace = val.join(',')
        },
		// 打开新增供应商对话框
		  openAddSupplierDialog() {
		    this.addSupplierDialogVisible = true;
		    this.supplierForm = {
		     supplierName: '',
		     contact: '',
		     contactPhone: '',
		     permitNumber: '',
		     address: '',
		     status: 1, // 默认启用
		     remark: ''
		    };
		  },
		// 关闭供应商对话框
		handleSupplierDialogClose(done) {
			done();
		},
					  
		// 保存供应商 / 提交表单
		async handleSubmit() {
		  this.$refs.supplierForm.validate(async (valid) => {
			if (valid) {
			  this.loading = true;
			  try {
				// 调用新增供应商API
				let res = await addSupplierEntity(this.supplierForm);
				
				if (res.code === 200) {
				  this.$message.success(res.message);
				  
				  // 1. 关闭新增供应商对话框
				  this.addSupplierDialogVisible = false;
				  
				  // 2. 重新加载供应商列表
				  await this.getGys();
				  
				  // 3. 自动选择新添加的供应商
				  if (res.data && res.data.id) {
					this.addForm.supplierId = res.data.id;
					this.$message.success(`已自动选择新增供应商: ${res.data.name}`);
				  }
				  
				  // 4. 重置供应商表单
				  this.supplierForm = {
					supplierName: '',
					contact: '',
					contactPhone: '',
					permitNumber: '',
					address: '',
					status: 1, // 默认启用
					remark: ''
				  };
				  
				  // 5. 清除表单验证状态
				  this.$nextTick(() => {
					if (this.$refs.supplierForm) {
					  this.$refs.supplierForm.clearValidate();
					}
				  });
				} else {
				  this.$message.error(res.message || '新增失败');
				}
			  } catch (error) {
				console.error('保存供应商出错:', error);
				this.$message.error('保存供应商失败');
			  } finally {
				this.loading = false;
			  }
			}
		  });
		},
        // db events
        // 给单元格绑定横向和竖向的index，这样就能确定是哪一个单元格
        tableCellClassName({row, column, rowIndex, columnIndex}){
            row.index = rowIndex;
            column.index = columnIndex;
        },
        // 当input失去焦点的时候，隐藏input
        hideInput(){
            this.currentCell = null;
        },
        // 获得当前双击的单元格的横竖index，然后拼接成一个唯一字符串用于判断，并赋给currentCell  // 拼接后类似这样："1,0","1,1",
        dbclick(row,column) {
            console.log(column.index);
        },
        // db events
        handledbRow(row, column, event){
            if(row){ this.addForm = row; this.watchDialogVisible = true } else { console.log('fail'); }
            // console.log(this.addForm);
            this.formdisabled = true
        },
        // col 里面包含了表头字段和名称，list 是表格数据
        columnWidth(col, list) {
          let prop = col.prop,lab = col.lab;
          let width = 40; // 设定一个最小值
          let maxlenStr = ""; // 最长字符串
          for (let info of list) { if (maxlenStr < (info[prop] + "").length) maxlenStr = info[prop] }
          width = Math.max(width, len(lab), len(maxlenStr));
          // 表格自带的内边距(20px) 自调
          return width + 24; // 这里加了 12px
          function len(str) {
            // 实际分配长度可根据需要自行调整
            let length = 12;
            for (const char of str + "") {
              // 英文小写字符 8px
              if ("a" <= char && char <= "z") length += 8;
              // 英文大写字符 8px
              else if ("A" <= char && char <= "Z") length += 8;
              // 中文字符 28px
              else if (char >= "\u4e00" && char <= "\u9fa5") length += 28;
              // 其他 8px
              else length += 12;
            }
            return length;
          }
        },
        // 内层
        innerColumnWidth(col, list){
            let prop = col.prop,lab = col.lab;
            let width = 28; // 设定一个最小值
            let maxlenStr = ""; // 最长字符串
            for (let info of list) { if (maxlenStr < (info[prop] + "").length) maxlenStr = info[prop] }
            width = Math.max(width, len(lab), len(maxlenStr));
            // 表格自带的内边距(20px) 自调
            return width + 24; // 这里加了 12px
            function len(str) {
                // 实际分配长度可根据需要自行调整
                let length = 12;
                for (const char of str + "") {
                  // 英文小写字符 8px
                  if ("a" <= char && char <= "z") length += 8;
                  // 英文大写字符 8px
                  else if ("A" <= char && char <= "Z") length += 8;
                  // 中文字符 22px
                  else if (char >= "\u4e00" && char <= "\u9fa5") length += 22;
                  // 其他 8px
                  else length += 12;
                }
                return length;
            }
        },
        // 挂载或销毁前后重新赋值后端参数
        getAddForm(){
            // 左侧提交表单
            this.addForm = addForm.map(v => {return v })[0]; // Form
            this.addMainForm = this.addForm.list[0]
            console.log(this.addForm,'原始的接口参数数据');
            // 定义数据来源
            this.formType = AccType.map(function(val) { return val })
            this.formMainType = AccMainType.map(function(val) { return val })
            // 解构赋值排除 list 属性 => 弃用
            // this.addHeadrForm = addForm.map(item => { let { list, ...newItem } = item; return newItem })[0];
        },
        //分页
        //每页条数改变触发
        handleSizeChange(val) {
            console.log(`每页 ${val} 条`);
            this.pageNum = val;
            this.loadData();
        },
        //当前条数改变触发
        handleCurrentChange(val) {
            console.log(`当前页: ${val}`);
            this.pageNum = val;
            this.loadData();
        },
        // 关闭最小化未保存清空的表单
        // 最小化对话框
        minimizeDialog() {
          this.addDialogVisible = false;
          this.isMinimized = true;
        },
        
        // 恢复对话框
        restoreDialog() {
          this.addDialogVisible = true;
          this.isMinimized = false;
        },
        // 库存序号判断
        async getPageListCheck(){
            if(this.addMainForm.drugId == ''){
                this.$message({ type: 'error', message: '请先选择正确的药品信息!'});
            } else if(this.addMainForm.prodentpNameId == ''){
                this.$message({ type: 'error', message: '关联的厂家序号错误，请重试。'});
            } else if(this.addMainForm.purcCnt > this.KcNum){
                // this.$message({ type: 'error', message: '调拨数量不能大于当前库存数量！【当前库存数量】：'+this.KcNum});
                this.$confirm('调拨数量不能大于【当前库存数量】！', '提示', {
				  confirmButtonText: 'OK',
				  cancelButtonText: '取消',
				  type: 'warning'
				}).then(() => {}).catch(() => {
				  this.$message({ type: 'info', message: '已取消'});          
				});
                this.addMainForm.purcCnt = 1;
            }
        },
        // 启用编辑状态（独立编辑模式）
        // 启用编辑状态
        enableEditing(row) {
          // 禁用底部所有按钮
          this.isEditing = true;
          
          // 先取消其他行的编辑状态
          this.tableData.forEach(item => {
            if (item.editing && item !== row) {
              this.$set(item, 'editing', false);
            }
          });
          
          // 保存原始数据用于取消编辑时恢复
          this.$set(row, '_originalData', JSON.parse(JSON.stringify(row)));
          this.$set(row, 'editing', true);
        },
        
        // 保存编辑
        saveEdit(row) {
          // 验证出库数量是否有效
          if (!row.apllyAmt || row.apllyAmt <= 0) {
            this.$message.error('出库数量必须大于0');
            return;
          }
          
          if (row.apllyAmt > row.purcCnt) {
            this.$message.error(`出库数量不能大于库存数量（当前库存：${row.purcCnt}）`);
            return;
          }
          
          // 重新计算当前行金额
          row.retnAmt = row.retnPric * row.apllyAmt;
          row.saleAmt = row.salePric * row.apllyAmt;
          
          // 退出编辑状态
          this.$set(row, 'editing', false);
          delete row._originalData;
          
          // 重新计算合计
          this.calculateTotals();
          
          // 启用底部按钮
          this.isEditing = false;
          
          this.$message.success('保存成功');
        },
        
        // 取消编辑
        cancelEdit(row) {
          // 恢复原始数据
          if (row._originalData) {
            Object.assign(row, row._originalData);
            delete row._originalData;
          }
          
          // 退出编辑状态
          this.$set(row, 'editing', false);
          
          // 启用底部按钮
          this.isEditing = false;
        },
         // 处理数量变化
         handleAmountChange(row) {
           // 确保是数字
           row.apllyAmt = Number(row.apllyAmt) || 0;
           
           // 实时验证库存数量
           if (row.apllyAmt > row.purcCnt) {
             this.$message.warning(`出库数量不能大于库存数量（当前库存：${row.purcCnt}）`);
             row.apllyAmt = row.purcCnt;
             return;
           }
           
           // 验证非负数
           if (row.apllyAmt < 0) {
             row.apllyAmt = 0;
             return;
           }
           
           // 计算当前行金额
           row.retnAmt = row.retnPric * row.apllyAmt;
           row.saleAmt = row.salePric * row.apllyAmt;
         }, 
          // 计算合计（独立计算）
          calculateTotals() {
            this.cbValue = this.tableData.reduce((sum, item) => {
              return sum + (Number(item.retnAmt) || 0);
            }, 0);
            
            this.lsValue = this.tableData.reduce((sum, item) => {
              return sum + (Number(item.saleAmt) || 0);
            }, 0);
            
            // 更新表单总金额（不影响其他数据）
            this.addForm.costAmt = this.cbValue;
            this.addForm.saleAmt = this.lsValue;
          },
        // 编辑处理字符串包裹的纯数字类型
        convertNumericStrings(obj) {
          if (typeof obj !== 'object' || obj === null) {
            return obj; // 非对象直接返回
          }
        
          // 处理数组
          if (Array.isArray(obj)) {
            return obj.map(item => this.convertNumericStrings(item));
          }
        
          // 处理普通对象
          const result = {};
          for (const key in obj) {
            if (obj.hasOwnProperty(key)) {
              const value = obj[key];
              if (typeof value === 'string' && /^\d+$/.test(value)) {
                // 字符串全为数字，转换为数字类型
                result[key] = Number(value);
              } else if (typeof value === 'object') {
                // 递归处理嵌套对象或数组
                result[key] = this.convertNumericStrings(value);
              } else {
                // 其他情况直接保留
                result[key] = value;
              }
            }
          }
          return result;
        },
		// 重置所有表单和状态
		resetAllForms() {
		  // 重置主表单
		  this.addForm = addForm.map(v => ({ ...v }))[0];
		  
		  // 重置明细表单
		  this.addMainForm = { ...this.addForm.list[0] };
		  
		  // 重置表格数据
		  this.tableData = [];
		  
		  // 重置金额合计
		  this.cbValue = '';
		  this.lsValue = '';
		  
		  // 重置其他状态
		  this.isEditing = false;
		  this.purcType = '1';
		  this.unt = '';
		  this.minUnt = '';
		  this.packNum = 0;
		  this.getMinMax = 0;
		  
		  // 重置表单验证
		  if (this.$refs.addForm) {
		    this.$refs.addForm.resetFields();
		  }
		  if (this.$refs.addMainForm) {
		    this.$refs.addMainForm.resetFields();
		  }
		  
		  // 重置当前日期时间
		  this.getNowDateTime();
		},
        // 打开最小化未保存清空的表单
        // restoreDialog() {
        //     this.addDialogVisible = true;
        //     this.isMinimized = false;
        // },

        // 关闭对话框处理
        handleClose(done) {
          // 如果是最小化状态，不执行关闭逻辑
          if (this.isMinimized) {
            return;
          }
          
          this.$confirm('关闭此界面会清空现已选择的内容, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            // 完全重置表单
            this.resetAllForms();
            done();
          }).catch(() => {
            this.$message({ type: 'info', message: '已取消' });          
          });
        },
		
    },
    
}
</script>

<style lang="less" scoped>
	.dialog-header {
	  display: flex;
	  height: 28px;
	  justify-content: space-between;
	  align-items: center;
	  width: 100%;
	  span{
		  color: #fff;
		  font-size: 12px;
	  }
	  .header-buttons {
	    display: flex;
	    align-items: center;
	    
	    /deep/ .el-button {
	      padding: 0;
	      margin-left: 8px;
	      color: #fff;
	      
	      &:hover {
	        color: #409EFF;
	        background-color: transparent;
	      }
	    }
	  }
	}
	#optionItem {
		width: 100%;
		height: 100%;
		display: flex;
		align-items: center;
		text-align: left;
		justify-content: space-around;
		span{
			padding-left: 8px;
			border: 1px solid #f1f1f1;
			display: inline-block;
			width: 128px;
			font-size: 12px;
			// height: 26px;
			// line-height: 26px;
			white-space: nowrap;      /* 禁止换行 */
			overflow: hidden;         /* 隐藏溢出内容 */
			text-overflow: ellipsis;  /* 溢出显示省略号 */
		}
	}
    /deep/ .el-dialog__body{
        padding: 12px;
    }
    /deep/ .el-dialog__header{
        padding: 4px;
        line-height: 28px;
        background-color: #007bb0;
    }
    /deep/ .el-dialog__title{
        color: #fff;
        font-size: 14px;
    }
    /deep/ .el-dialog__headerbtn{
        top: 10px;
    }
    /deep/ .el-dialog__body{
        padding: 8px;
    }
    /deep/ .el-dialog__headerbtn .el-dialog__close{
        color: #fff;
    }
    /deep/ .el-dialog__headerbtn .el-dialog__close:hover{
        background-color: brown;
    }
    /deep/ .el-table .cell{
        font-size: 12px;
        font-weight: 400;
        color: #0c0c0c;
        text-align: center;
    }
    
    /deep/ .el-table .el-table__cell{
        padding: 8px 0;
    }
.layout-app{
    width: 100%;
    height: 100%;
    display: flex;
    background-color: f8f8f8;
    /* 对话框样式 */
    .minimizable-dialog {
      transition: all 0.3s;
      transform: rotate(180deg);
    }
    .minimized-button {
      transform: scale(1.1);
      cursor: pointer;
    }
    .minimized-button {
      position: fixed;
      right: 20px;
      bottom: 50%;
      width: 40px;
      height: 40px;
      border-radius: 50%;
      background-color: #409eff;
      color: white;
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
      z-index: 9999;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      animation: floatIn 0.3s;
    }
    @keyframes floatIn {
      from {
        transform: scale(0) translateY(100%);
        opacity: 0;
      }
      to {
        transform: scale(1) translateY(0);
        opacity: 1;
      }
    }
    .addAcc{
        // self
        // 选项卡
        .tabs{
            .tabsMain{
                display: flex;
                flex-direction: column;
                justify-content: space-between;
                align-items: center;
                width: 100%;
                .table{
                    width: 100%;
                    margin-top: 12px;
					span{
						display: inline-block;
						font-size: 12px;
						// width: 168px;
						height: 40px;
						line-height: 40px;
						white-space: nowrap;      /* 禁止换行 */
						overflow: hidden;         /* 隐藏溢出内容 */
						text-overflow: ellipsis;  /* 溢出显示省略号 */
					}
                }
                .total{
                    display: flex;
                    height: 48px;
                    align-items: center;
                    span{
                        font-size: 12px;
                    }
                }
                // 第一层头部表单
                .headerForm{
                    /deep/ .el-divider__text{
                        padding: 0;
                    }
                    
                    /deep/ .el-input{
                        width: 100%;
                    }
                    /deep/ .el-select >.el-input{
                        width: 100%;
                    }
                    padding: 8px;
					/deep/ .el-form-item{
						margin-bottom: 6px;
					}
                    /deep/ .el-form-item__label{
                        display: flex;
                        justify-content: start;
                        font-size: 12px;
                        padding: 0;
                    }
                    /deep/ .el-input--mini .el-input__inner{
                        height: 26px;
                    }
                }
                // 第二层主体表单
                .mainForm{
					padding: 12px;
					.input-with-select{
						/deep/ .el-select .el-input {
						    width: 108px;
						}
					}
					/deep/ .el-select-dropdown__item{
						border: 1px solid #eeeeee;
						padding: 0;
						height: 28px;
						#optionItem {
							width: 100%;
							height: 100%;
							display: flex;
							align-items: center;
							text-align: center;
							justify-content: space-around;
							span{
								display: inline-block;
								font-size: 12px;
								// width: 168px;
								height: 40px;
								line-height: 40px;
								white-space: nowrap;      /* 禁止换行 */
								overflow: hidden;         /* 隐藏溢出内容 */
								text-overflow: ellipsis;  /* 溢出显示省略号 */
							}
						}
					}
					/deep/ .input-with-select .el-input-group__prepend {
					    background-color: #fff;
					}
                    
                    /deep/ .el-input{
                        width: 100%;
                    }
                    /deep/ .el-select >.el-input{
                        width: 100%;
                    }
					/deep/ .el-form-item{
						margin-bottom: 6px;
					}
                    /deep/ .el-form-item__label{
                        display: flex;
                        justify-content: center;
                        font-size: 10px;
                        padding: 0;
                    }
                    /deep/ .el-input--mini .el-input__inner{
                        height: 26px;
                    }
                    /deep/ .el-date-editor.el-input, .el-date-editor.el-input__inner{
                        width: 100%;
                    }
                }
            }	
        }
        .dialog-footer{
            display: flex;
            justify-content: right;
        }
    }
    .innerModel{
        .innerModel-header{
            display: flex;
            align-items: center;
        }
        .innerModel-table{
            
        }
    }
    
}
</style>